package com.skateboard.reelviewtest;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.DecelerateInterpolator;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.skateboard.reelviewtest.gallery.GalleryLayoutManager;
import com.skateboard.reelviewtest.gallery.RecyclerViewAdapter;


public class RecyclerGalleryActivity extends AppCompatActivity implements GalleryLayoutManager.OnItemSelectedListener {
    private RecyclerView recyclerView;
    private RecyclerViewAdapter adapter;
    private TextView tvPos;
    private float mTranslationRatio = 0.15f;
    private float mDegToRad = 1.0f / 180.0f * (float) Math.PI;
    private int mCircleOffset = 140;
    private int centerToLiftDistance; //RecyclRecyclerGalleryActivityerView款度的一半 ,也就是控件中间位置到左部的距离

    private DecelerateInterpolator decelerateInterpolator = new DecelerateInterpolator();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_gallery_view);
        tvPos =findViewById(R.id.tv_pos);
        init();
    }

    private void init() {
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    recyclerView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }

                centerToLiftDistance = recyclerView.getWidth() / 2;

            }
        });



        GalleryLayoutManager manager = new GalleryLayoutManager(GalleryLayoutManager.HORIZONTAL);

        //设置默认选中的位置
        manager.attach(recyclerView, 1000000);
        adapter = new RecyclerViewAdapter(this);
        recyclerView.setAdapter(adapter);
        manager.setOnItemSelectedListener(this);
        adapter.setmOnItemClickListener(new RecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, String data) {
                // 支持手动点击滑动切换
                scrollToPos(Integer.valueOf(data));
            }
        });


        //添加Rv滚动监听
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                //遍历每一个条目，设置对应的偏移量
                final int count = recyclerView.getChildCount();

                //屏幕中间线
                float rvCenterX = recyclerView.getWidth()/2;


                for (int i = 0; i < count; ++i) {
                    View v = recyclerView.getChildAt(i);


                    float halfWidth = v.getWidth() * 0.5f;
                    float parentHalfWidth = recyclerView.getWidth() * 0.5f;
                    float x = v.getX();
                    float rot = parentHalfWidth - halfWidth - x;
                    float transY = -1 * (float) (-Math.cos(rot * mTranslationRatio * mDegToRad) + 1) * mCircleOffset;

                    System.out.println("偏移距离:"+((-Math.cos(rot * mTranslationRatio * mDegToRad))+1));



                    /* ***********根据余弦公司方式计算缩放比例*********** */
                    //对应条目移动距离
                    float distance = Math.abs(v.getX() -rvCenterX);
                    //移动的距离和屏幕宽度的比例值
                    float apartScale = distance/recyclerView.getWidth();
                    //把卡片移动范围固定到 -π/4到 +π/4这一个范围内(-0.1是为了得到的值相对大一些)
                    float scale = (float) (Math.abs(Math.cos(apartScale* Math.PI/4))-0.1);
                    System.out.println("对应的缩放倍数:"+scale);
                    v.setScaleY(scale);

                    //计算缩放的高度
                    float oladHeight = v.getHeight();
                    float nowHeight = oladHeight*(1-scale);
                    float halfScH = (oladHeight-nowHeight)/2;

                    //设置透明度
                    v.setAlpha((float) (scale-0.3));



                    //设置Y方向偏移
                    v.setTranslationY(calculateTranslate(v.getLeft(),recyclerView.getWidth()));
                    if (i==4){
                        System.out.println("间距:中间的条目间距:"+calculateTranslate(v.getLeft(),recyclerView.getWidth()));
                    }else if (i==3){
                        System.out.println("间距:左边的条目间距:"+calculateTranslate(v.getLeft(),recyclerView.getWidth()));
                    }else if (i==5){
                        System.out.println("间距:右边的条目间距:"+calculateTranslate(v.getLeft(),recyclerView.getWidth()));
                    }

                   // v.setTranslationY(transY);





                }

            }
        });
    }

    @Override
    public void onItemSelected(RecyclerView recyclerView, View item, int position) {
        //总共6个
        tvPos.setText("当前位置:"+position%6);
    }


    /**
     * 滚动到对应条目
     */
    public void scrollToPos(int position){
        GalleryLayoutManager linearLayoutManager = (GalleryLayoutManager) recyclerView.getLayoutManager();
        View childView = linearLayoutManager.findViewByPosition(position);
        Log.i("ccb", "滑动后中间View的索引: " + position);
        //把当前View移动到居中位置
        if (childView == null) return;
        int childVhalf = childView.getWidth() / 2;
        int childViewLeft = childView.getLeft();
        int viewCTop = centerToLiftDistance;
        int smoothDistance = childViewLeft - viewCTop + childVhalf;

        recyclerView.smoothScrollBy(smoothDistance, 0, decelerateInterpolator);

    }

    float w;
    private  float calculateTranslate(int left,int rvWidth){
        float result =0;
        w = rvWidth- dip2px(this,69);//条目的宽度
        float halfW = w/2;
        result =  Math.abs(halfW - left);
        result = halfW - result;
        return result/4;
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
